/**
 * 
 */
package com.yunyike.controller.coupon;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yunyike.constants.CartConstants;
import com.yunyike.constants.CommonConstant;
import com.yunyike.constants.CouponConstants;
import com.yunyike.constants.RequestConstant;
import com.yunyike.constants.ResponseConstant;
import com.yunyike.controller.BaseController;
import com.yunyike.dto.cart.CartDTO;
import com.yunyike.model.Coupon;
import com.yunyike.model.User;
import com.yunyike.redis.JedisManager;
import com.yunyike.response.Response;
import com.yunyike.service.ICartService;
import com.yunyike.service.ICouponService;
import com.yunyike.utils.UserUtils;

/**
 * @author zhengqiang.shi
 * 2015年11月26日 下午10:33:00
 */
@Controller
@RequestMapping(value=RequestConstant.COUPON)
public class CouponController extends BaseController {

	private Logger log = LoggerFactory.getLogger(CouponController.class);
	
	@Autowired
	private ICouponService couponService;
	
	@Autowired
	private ICartService cartService;
	
	/**
	 * 结算页获取优惠券数量
	 * @param shopId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value=RequestConstant.COUPON_QTY)
	public void findCouponQtyBySettlement(HttpServletResponse response,String [] merchandiseId){
		
		Response res = new Response();
		
		log.info("coupon.qty ,merchandiseId:{}",Arrays.toString(merchandiseId));
		
		if(merchandiseId == null || merchandiseId.length < 1){
			res.getResult().setCode(CommonConstant.NUMBER__1);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__1));
			returnDatas(res, response);
			return;
		}
		
		// 当前用户
		User user = getCurrentUser();
		
		// 获取当前结算的商品信息
		CartDTO cartDTO;
		try {
			cartDTO = cartService.settlement(user, Arrays.asList(merchandiseId));
		} catch (Exception e) {
			log.error("coupon.qty get cartDTO has error:"+e.getMessage(),e);
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		// 获取优惠券数量
		Integer couponQty;
		try {
			couponQty = couponService.findCouponQtyBySettlement(user, cartDTO);
		} catch (Exception e) {
			log.error("coupon.qty findCouponQty has error:"+e.getMessage(),e);
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		res.setData(couponQty);
		returnDatas(res, response);
	}
	
	/**
	 * 优惠券列表 结算页
	 * @param shopId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value=RequestConstant.COUPON_LIST)
	public void findCoupon(String [] merchandiseId,
			HttpServletRequest request, HttpServletResponse response){
		
		Response res = new Response();
		
		log.info("coupon.list ,merchandiseId:{}",Arrays.toString(merchandiseId));
		
		if(merchandiseId == null || merchandiseId.length < 1){
			res.getResult().setCode(CommonConstant.NUMBER__1);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__1));
			returnDatas(res, response);
			return;
		}
		
		// 当前用户
		User user = getCurrentUser();
		
		// 获取当前结算的商品信息
		CartDTO cartDTO;
		try {
			cartDTO = cartService.settlement(user, Arrays.asList(merchandiseId));
		} catch (Exception e) {
			log.error("coupon.list get cartDTO has error:"+e.getMessage(),e);
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		// 获取优惠券列表
		List<Coupon> list;
		try {
			list = couponService.findCouponsBySettlement(user, cartDTO);
		} catch (Exception e) {
			log.error("coupon.list findCoupon has error:"+e.getMessage(),e);
			res.getResult().setCode(CommonConstant.NUMBER__3);
			res.getResult().setMessage(ResponseConstant.message.get(CommonConstant.NUMBER__3));
			returnDatas(res, response);
			return;
		}
		
		res.setData(list);
		returnDatas(res, response);
	}
	
	/**
	 * 优惠券列表 个人中心
	 * @param shopId
	 * @return
	 */
	//@RequestMapping(value=RequestConstant.COUPON_FIND+"/{couponType}")
	public String findCouponByUser(@PathVariable Integer couponType,
			HttpServletRequest request, HttpServletResponse response,Model model){
		
		// 当前用户
		User user = getCurrentUser();
		
		if(couponType == null){
			couponType = CommonConstant.NUMBER_0;
		}
		
		log.info("request param:couponType:"+couponType);
		
		Coupon coupon = new Coupon();
		coupon.setUserId(user.getUserId());
		coupon.setCouponType(couponType);
		
		// 获取优惠券
		List<Coupon> coupons = couponService.findCouponByCondition(coupon);
		model.addAttribute("couponType", couponType);
		if(coupons == null || coupons.isEmpty()){
			return ResponseConstant.USER_COUPON;
		}
		
		// 设置优惠券状态
		for (Coupon c : coupons) {
			Date couponEndDate = c.getCouponEndDate();
			Date currentDate = new Date();
			// 已过期
			if(currentDate.after(couponEndDate)){
				c.setCouponStatus(CouponConstants.COUPON_STATUS_2);
				continue;
			}
		}
		
		model.addAttribute("coupons", coupons);
		
		return ResponseConstant.USER_COUPON;
	}
	
	/**
	 * 使用优惠券 结算
	 * @param shopId
	 * @return
	 */
	@RequestMapping(value=RequestConstant.COUPON_USE,method=RequestMethod.POST)
	public String useCoupon(String couponId, Integer couponType, Model model, 
			HttpServletRequest request, HttpServletResponse response){
		
		// 当前用户
		User user = getCurrentUser();
		
		log.info("request param:couponId:"+couponId);
		
		// 使用优惠券
		String sessionId = UserUtils.getSessionId(request, response);
		couponService.useCoupon(user, couponId, couponType,sessionId);
		
		// 结算地址
		String str = JedisManager.getString(CartConstants.settlementUrlKey(sessionId));
		
		// 调用结算地址
		return ResponseConstant.REDIRECT+RequestConstant.CART+RequestConstant.CART_SETTLEMENT+"/"+str;
	}
}
